import { otherApi } from '@/request/api'
import { useModal } from '@/utils'
import { to } from 'await-to-js'
import { isEmpty } from 'lodash-es'
import ajax from './http'

interface Options {
  filePath: string
}

interface UploadRes {
  fileExt: string
  fileName: string
  fileSize: string
  fileType: string
  fileUrl: string
}

export default async function (options: Options): Promise<UploadRes> {
  // 使用一个需要身份验证的接口来检测登录并处理刷新token
  const [preVerifyErr] = await to(otherApi.fetchAddress())
  if (preVerifyErr) {
    return Promise.reject(preVerifyErr)
  }

  const header: Record<string, any> = {}
  // #ifdef H5
  header['applet-id'] = import.meta.env.VITE_H5_APPLETID
  // #endif
  // #ifdef MP-WEIXIN || MP-ALIPAY
  header['applet-id'] = uni.getAccountInfoSync().miniProgram.appId
  // #endif
  // #ifdef MP-TOUTIAO
  header['applet-id'] = tt.getEnvInfoSync().microapp.appId
  // #endif
  const token = uni.getStorageSync('token')
  if (!isEmpty(token)) {
    header.Authorization = `Bearer ${token}`
  }

  const url = await ajax.getURL({ url: '/xyzl-org/sys-common/upload' })

  const [err, res] = await to(
    uni.uploadFile({
      url,
      header,
      filePath: options.filePath,
      name: 'file',
    }),
  )

  if (err) {
    useModal({
      content: '上传失败',
      showCancel: false,
      confirmText: '确定',
    })
    return Promise.reject(err)
  }

  const data = JSON.parse(res.data)
  // useConsole?.log('upload', data)

  if (data.code !== 0) {
    useModal({
      title: '上传失败',
      content: data.msg,
      showCancel: false,
      confirmText: '确定',
    })
    return Promise.reject(new Error('UploadError:data.code!==0'))
  }

  return data.data
}
